package main

import (
	"context"
	"log"
	"net"
	pb "neu/liuhy/gorpc/proto"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
)

// 实现Greeter服务接口， 通过UnimplementedGreeterServer关联到proto生成的两个文件
type server struct {
	pb.UnimplementedGreeterServer
}

// SayHello实现单个问候
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	log.Printf("Received: %v", in.Name)
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

// SayHelloBatch实现批量问候
func (s *server) SayHelloBatch(ctx context.Context, in *pb.HelloBatchRequest) (*pb.HelloBatchReply, error) {
	log.Printf("Received batch: %v", in.Names)

	messages := make([]string, len(in.Names))
	for i, name := range in.Names {
		messages[i] = "Hello " + name
	}

	return &pb.HelloBatchReply{Messages: messages}, nil
}

func main() {
	// 监听50051端口
	listener, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	// 创建gRPC服务器
	rpcServer := grpc.NewServer(
		grpc.MaxConcurrentStreams(1000),
		grpc.KeepaliveParams(keepalive.ServerParameters{
			MaxConnectionIdle:     30 * time.Second, // 连接空闲 30s 触发保活
			MaxConnectionAge:      2 * time.Hour,    // 连接最大存活 2h，避免长期占用
			MaxConnectionAgeGrace: 5 * time.Minute,  // 存活期到后， grace 时间内处理完请求
			Time:                  10 * time.Second, // 每 10s 发一次保活探测
			Timeout:               5 * time.Second,  // 探测超时时间
		}),
	)

	// 注册Greeter服务 , rpcServer 是 gRPC 服务器实例，&server{} 是 Greeter 服务的实现
	pb.RegisterGreeterServer(rpcServer, &server{})

	log.Println("Server listening at", listener.Addr())

	// 启动服务器
	if err := rpcServer.Serve(listener); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
